<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class SignModel extends Model
{
    //签到
    protected $table='sign_user';

    public function user(){
        return $this->belongsTo(UserModel::class,'user_id','id');
    }

    public function personal_sign($request,$class_work){
        DB::beginTransaction(); //开启事务
        try {
            //重新获取用户信息
            $user = UserModel::select(['id','company_id','user_integral','total_integral'])
                ->where('id',$request->user()->id)
                ->first();

            $integral_day = SetSignModel::where('company_id',$request->user()->company_id)->value('integral_day');
            if($class_work->is_points == 1){
                $integral_day = $class_work->points_value;
            }

            $user->total_integral = (int)$user->total_integral + (int)$integral_day;
            $user->user_integral = (int)$user->user_integral + (int)$integral_day;
            $user->save();

            $num = $this->where('user_id',$request->user()->id)
                ->orderBy('id','desc')
               // ->where('sign_type',1)
                ->value('num');
            $sign_num = $num;
            $this->fresh();

            $sign_num = !empty($sign_num)?$sign_num:0;
            $this->user_id = $request->user()->id;

            $this->num = $sign_num + 1;
            $this->integral = $integral_day;

            $res = $this->save();
            DB::commit();
            return $res;
        }catch (\Exception $e) {
            DB::rollBack();
            Log::info('用户个人签到失败'.$e -> getMessage());
            return false;
        }
    }

    public function sign_user_order($company_id){
        return $this->where('company_id',$company_id)
            ->select([
                'user_id',
                \DB::raw("sum(integral) as total_integral"),
            ])
            ->with([
                'user'=>function($q){
                    $q->select([
                        'id',
                        'nickname',
                        'avatar',
                    ]);
                },
            ])
            ->orderBy('integral','desc')
            ->paginate(15);

    }

}
